package com.jlcloud.core.oauth2.service.impl;

import lombok.AllArgsConstructor;
import com.jlcloud.core.oauth2.constant.OAuth2ClientConstant;
import com.jlcloud.core.oauth2.provider.OAuth2Request;
import com.jlcloud.core.oauth2.service.OAuth2Client;
import com.jlcloud.core.oauth2.service.OAuth2ClientService;
import com.jlcloud.core.tool.utils.Func;
import com.jlcloud.core.tool.utils.StringPool;
import com.jlcloud.core.tool.utils.StringUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Arrays;
import java.util.Optional;

/**
 * 获取客户端详情
 *
 * @author By: JlCloud <br>
 * @Package: com.jlcloud <br>
 * @CreateTime: 2024-12-03 21:45 <br>
 * @Copyright: 2021 www.jilianjituan.com Inc. All rights reserved. <br>
 * @Caution 注意：本内容仅限于冀联人力集团内部传阅，禁止外泄以及用于其他的商业目的 <br>
 */
@AllArgsConstructor
public class OAuth2ClientDetailService implements OAuth2ClientService {

	private final JdbcTemplate jdbcTemplate;

	@Override
	public OAuth2Client loadByClientId(String clientId) {
		return loadByClientId(clientId, null);
	}

	@Override
	public OAuth2Client loadByClientId(String clientId, OAuth2Request request) {
		try {
			return jdbcTemplate.queryForObject(OAuth2ClientConstant.DEFAULT_SELECT_STATEMENT, new BeanPropertyRowMapper<>(OAuth2ClientDetail.class), clientId);
		} catch (Exception ex) {
			return null;
		}
	}

	@Override
	public boolean validateClient(OAuth2Client client, String clientId, String clientSecret) {
		return Optional.ofNullable(client)
			.map(c -> StringUtil.equals(clientId, c.getClientId()) && StringUtil.equals(clientSecret, c.getClientSecret()))
			.orElse(false);
	}

	@Override
	public boolean validateRedirectUri(OAuth2Client client, String redirectUri) {
		return Optional.ofNullable(client)
			.map(c -> StringUtil.equals(redirectUri, c.getWebServerRedirectUri()))
			.orElse(false);
	}

	@Override
	public boolean validateGranter(OAuth2Client client, String grantType) {
		return Optional.ofNullable(client)
			.map(c -> Arrays.stream(Func.split(c.getAuthorizedGrantTypes(), StringPool.COMMA))
				.anyMatch(s -> s.trim().equals(grantType)))
			.orElse(false);
	}

}
